package com.snow.fkisoftstone;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.snow.fkisoftstone.adapter.WorkAdapter;
import com.snow.fkisoftstone.bean.WorkTime;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private PermissionsManager permissionsManager;

    private RecyclerView recyclerView;

    private TextView tvErr;

    private WorkAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.rcv);
        tvErr=findViewById(R.id.tvErr);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new WorkAdapter(null);
        recyclerView.setAdapter(adapter);

        if (!isAccessibilitySettingsOn(this,
                TimerService.class.getName())) {// 判断服务是否开启
            jumpToSettingPage();// 跳转到开启页面
        } else {
            Toast.makeText(this, "服务已开启", Toast.LENGTH_SHORT).show();
            //do other things...
        }
        permissionsManager = new PermissionsManager(this) {
            @Override
            public void authorized(int requestCode) {
                showInfo();
            }

            @Override
            public void noAuthorization(int requestCode, String[] lacksPermissions) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("R.string.dialog_tip");
                builder.setMessage("R.string.dialog_misspermiss");
                builder.setPositiveButton("R.string.dialog_setpermiss",
                        (dialog, which) -> PermissionsManager.startAppSettings(MainActivity.this));
                builder.create().show();
            }

            @Override
            public void ignore() {
                showInfo();
            }
        };
        // 要校验的权限
        String[] PERMISSIONS = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        // 检查权限
        permissionsManager.checkPermissions(0, PERMISSIONS);
    }

    private void showInfo() {
        Date d = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM");
        String monthStr = sbf.format(d);
        String fileName = String.format(TimerService.PATH_DATE, monthStr);
        StringBuilder s = FileUtils.readFile(fileName, "UTF-8");
        if (!TextUtils.isEmpty(s)){
            try {
                Gson gson = new Gson();
                List<WorkTime> workTimes = gson.fromJson(s.toString(),
                        new TypeToken<List<WorkTime>>() {
                        }.getType());
                adapter.setmWorkList(workTimes);
                adapter.notifyDataSetChanged();
            }catch (Exception e){
                e.printStackTrace();
                tvErr.setVisibility(View.VISIBLE);
                tvErr.setText("获取信息异常");
            }
        }else {
            tvErr.setVisibility(View.VISIBLE);
            tvErr.setText("无打卡数据，请打卡一天后查看。");
        }
    }

    private String loadData() {
        StringBuilder builder=new StringBuilder("\n-----------------------");
        List<String> stringList = FileUtils.readFileToList(TimerService.PATH_LOG, "UTF-8");
        for (String item:stringList){
            if (item.contains("click")){
                continue;
            }
            String[] datas=item.split("##");
            builder.append(item.replace("##","  "));
            builder.append("\n");
        }
        return builder.toString();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissionsManager != null)
            permissionsManager.recheckPermissions(requestCode, permissions, grantResults);
    }

    //判断自定义辅助功能服务是否开启
    public static boolean isAccessibilitySettingsOn(Context context, String className) {
        if (context == null) {
            return false;
        }
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager != null) {
            List<ActivityManager.RunningServiceInfo> runningServices =
                    activityManager.getRunningServices(100);// 获取正在运行的服务列表
            if (runningServices.size() < 0) {
                return false;
            }
            for (int i = 0; i < runningServices.size(); i++) {
                ComponentName service = runningServices.get(i).service;
                if (service.getClassName().equals(className)) {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    }


    //跳转到设置页面无障碍服务开启自定义辅助功能服务
    public void jumpToSettingPage() {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}